/**
 * Created by Frank on 5/19/15.
 */

// var fileTypeArray = ["uploadBaseInfo", "uploadBaseInfo", "uploadClassRoom",
//     "uploadCoursePlan","uploadElectiveTeachingPlan","uploadStudentCourseInfo"];
// var titleArray = ["上传课时和教师信息", "上传课时和教师信息", "上传专业教室信息","上传课程表","上传走班课程信息","上传学生选课情况"];
// var imgArray = ["baseInfo.png","baseInfo.png", "classroom.png","allCoursePlan.png","e_teachingPlan.png","e_studentCourseInfo.png"];
// var templateArray = ["getCourseTeacherTemp", "getCourseTeacherTemp", "getClassRoomTemp","getAllCoursePlan", "getElectiveTeachingPlanTemp", "getStudentCourseInfoTemp"];
// var promptInfoArray = ["请按照模板填写信息，其中”4+1“表示4节单堂一节连堂共六课时。",
//     "请按照模板填写信息，其中”4+1“表示4节单堂一节连堂共六课时。",
//     "请按照模板填写教室信息，注意教室课程名称要与课时老师分配信息中的课程名称保持一至。",
//     "请上传课程表信息!","请上传走班课程信息!","请上传学生选课信息!"];


var fileTypeArray = ["uploadBaseInfo", "uploadBaseInfo", "uploadClassRoom", "uploadTeachingGroup", "uploadCoursePlan", "uploadTeachingPlan", "uploadSubjectCourseInfo", "uploadStudentCourseInfo", "uploadCourseTeacherInfo", "uploadClassRoomInfo", "uploadClassInfoClassRoom"];
var titleArray = ["上传课时和教师信息", "上传课时和教师信息", "上传专业教室信息", "上传分层公选课安排信息", "上传课程表", "上传走班课程信息", "上传走班课程信息", "上传学生选课情况", "上传任课教师信息", "上传教室信息", "上传班级教室信息"];
var imgArray = ["baseInfo.png", "baseInfo.png", "classroom.png", "layerCourse.png", "allCoursePlan.png", "XX.png", "courseTeacher.png", "e_studentCourseInfo.png", "courseTeacherInfo.png", "classRoomInfo.png", "classInfoClassRoomInfo.png"];
var templateArray = ["getCourseTeacherTemp", "getCourseTeacherTemp", "getClassRoomTemp", "getLayeringCourse", "getAllCoursePlan", "getElectiveTeachingPlanTemplate", "getSubjectCourseInfoTemp", "getStudentCourseInfoTemp", "getCourseTeacherInfoTemplate", "getClassRoomInfoTemplate"];
var promptInfoArray = ["请按照模板填写信息，其中”4+1“表示4节单堂一节连堂共六课时。",
    "请按照模板填写信息，其中”4+1“表示4节单堂一节连堂共六课时。",
    "请按照模板填写教室信息，注意教室课程名称要与课时老师分配信息中的课程名称保持一至。",
    "排课必须的基础信息包括”年级”、”班级”、”课时分配”、”教师安排”、”专业教室安排”等，请按照 模板 填写并导入。",
    "请上传课程表信息！",
    "请上传走班课程信息！",
    "请上传走班课程信息！",
    "请上传学生选课信息！",
    "请上传任课教师信息！",
    "请上传教室信息！"];

var fileType = fileTypeArray[0];
var title = titleArray[0];
var img = imgArray[0];
var promptInfo = promptInfoArray[0];
var template = templateArray[0];
var $fileList = $("#thelist");
var studentCourseGradeId = "";
var postData;

//$(document).ready(function () {

//});
function showInfo() {

    $("#b_info").html(title);
    $("#imgexample").attr("src", "/static/Template/image/" + img)
    $("#down").attr("href", baseUrl + "/baseInfo/" + template.addTimestamp() + "&taskId=" + taskId);
    $("#divPrompt").html(promptInfo);
}


function createUploader() {
    var uploader = WebUploader.create({
        auto: true,
        swf: '/Static/webuploader/Uploader.swf',
        // 后台服务器文件上传地址
        // server: baseUrl + "/baseInfo/" + fileType,
        server: "/Utility/fileupload",
        // formData: postData,
        formData: { taskId: $("#taskId").val(), fileId: $("#fileId").val() },
        pick: '#picker',
        resize: false,
        accept: {
            title: 'Excel',
            extensions: 'xls',
            mimeTypes: 'application/excel'
        }
    });

    uploader.on('beforeFileQueued', function (file) {
        $("#uploadInfo").css("display", "none");
        if (file.ext.toLowerCase() == "xls") {
            if (fileType == "uploadStudentCourseInfo") {
                var index = parseInt($("#tabIndex").val());
                if (index < (parseInt($("#BaseCompleteIndex").val()) - 1)) {
                    return confirm("再次导入学生选课数据后，课程设置、教师分配以及手动排课模块所有信息将被清空，点击确定后，重新导入并清空原数据及其后续所有数据；点击取消后，取消导入操作。");
                }
            } else if (fileType == "uploadCourseTeacherInfo") {
                var index = parseInt($("#tabIndex").val());
                if (index < (parseInt($("#BaseCompleteIndex").val()) - 2)) {
                    return confirm("再次导入任课教师数据后，教师分配以及手动排课模块所有信息将被清空”，点击确定后，重新导入并清空数据；点击取消后，取消导入操作。");
                }
            } else if (fileType == "uploadSubjectCourseInfo") {
                var index = parseInt($("#tabIndex").val());
                if (index < (parseInt($("#BaseCompleteIndex").val()) - 1)) {
                    return confirm("再次导入学科课程数据后，学生选课、任课教师、教室管理、课程设置、教师分配以及手动排课模块所有信息将被清空”，点击确定后，重新导入并清空原数据及其后续所有数据；点击取消后，取消导入操作。");
                }
            }
            return true;
        }
        else {
            alertError("上传的文件格式不正确！");
            return false;
        }
    });
    // 当有文件添加进来的时候
    uploader.on('fileQueued', function (file) {
        // alert("文件添加进来le!");
        $fileList.append('<div id="' + file.id + '" class="item">' + ' ' + file.name + ' ' + '<p class="state">上传中...</p>' + '</div>');

    });
    uploader.on('uploadProgress', function (file, percentage) {
        var $li = $('#' + file.id),
            $percent = $li.find('.progress .progress-bar');
        // 避免重复创建
        if (!$percent.length) {
            $percent = $('<div class="progress progress-striped active">' +
            '<div class="progress-bar" role="progressbar" style="width: 0%">' +
            '</div>' +
            '</div>').appendTo($li).find('.progress-bar');
        }
        $li.find('p.state').text('上传中');
        $percent.css('width', percentage * 100 + '%');
    });

    // 文件上传成功
    uploader.on('uploadSuccess', function (file, response) {
        $('#' + file.id).find('p.state').text('已上传');
        // console.log(response);
        if (response.status) {
            // 重新刷新页面，并完成从 excel 到 table的转变。
            window.location.reload();
        }

        //if (response.code != undefined)  //成功
        //{
        //    if (response.code > 0) {
        //        if (fileType == "uploadBaseInfo") {
        //            searchBaseInfo();
        //            searchRoom();
        //            alertError(getErrorInfo(response));
        //        } else if (fileType == "uploadClassRoom") {
        //            searchRoom();
        //            $("#showSpecialClassRoomBtn").show();
        //            alertError(decodeURIComponent(response.msg));
        //        } else if (fileType == "uploadTeachingGroup") {
        //            searchPublicCourse();
        //        } else if (fileType == "uploadCoursePlan") {
        //            searchBaseInfo();
        //            searchRoom();
        //            $("#li0 a:first").click();//切换选项卡
        //            alertError(getErrorInfo(response));
        //        } else if (fileType == "uploadElectiveTeachingPlan") {
        //            searchElectiveBaseInfo();
        //            alertError(decodeURIComponent(response.msg));
        //        } else if (fileType == "uploadStudentCourseInfo") {
        //            studentCourseGradeId = "";
        //            searchStudentCourseInfo();
        //            setTabInfoForUploadButton(3);
        //            alertError(decodeURIComponent(response.msg));
        //        } else if (fileType == "uploadCourseTeacherInfo") {
        //            getCourseTeacherInfo();
        //            setTabInfoForUploadButton(5);
        //            tabButtonAvailable(3);
        //            alertError(decodeURIComponent(response.msg));
        //        }else if(fileType=="uploadSubjectCourseInfo"){
        //            getSubjectCourseInfos();
        //            setTabInfoForUploadButton(2);
        //            alertError(decodeURIComponent(response.msg));
        //        }else if(fileType == "uploadClassRoomInfo"){
        //            getClassRoomInfo();
        //            alertError(decodeURIComponent(response.msg));
        //        }else if(fileType=="uploadClassInfoClassRoom"){
        //            $("#showClassRoomBtn").show();
        //            searchClassInfoRoom();
        //            alertError(decodeURIComponent(response.msg));
        //        }
        //    }
        //    else {
        //        alertError(decodeURIComponent(response.msg));
        //    }
        //}
    });
    // 文件上传失败
    uploader.on('uploadError', function (file) {
        $('#' + file.id).find('p.state').text('上传失败');
        studentCourseGradeId = "";
    });
    // 文件上传完成。
    uploader.on('uploadComplete', function (file) {
        //$('#' + file.id).find('.progress').fadeOut();
        studentCourseGradeId = "";
        $('#' + file.id).fadeOut();
    });
}

function alertError(msg) {
    if (msg != null && msg != undefined && msg != "") {
        $("#uploadInfo").html(msg);
        $("#uploadInfo").show();//.fadeOut(4000);
    }
}

function getErrorInfo(response) {
    var obj = toJson(decodeURIComponent(response.data));
    if (obj != null && typeof (obj) == "object" && obj.length >= 1) {
        var tableHtml = new Array();
        tableHtml.push("以下规则没有导入成功：")
        tableHtml.push("<table width='100%'>");
        for (var i = 0; i < obj.length; i++) {
            tableHtml.push("<tr>");
            tableHtml.push("<td>" + obj[i].ruleTypeName + "</td>");
            tableHtml.push("<td>" + obj[i].ruleContent + "</td>");
            tableHtml.push("</tr>");
        }
        tableHtml.push("</table>");
        return tableHtml.join("");
    }
    return decodeURIComponent(response.msg);
}

function toJson(strJson) {
    try {
        if (typeof (strJson) == "object") {
            return strJson;
        }
        else {
            return eval("(" + strJson + ")");
        }
    }
    catch (e) {
        return strJson;
    }
}
/**
 * set the variables' value
 * @param fileTypeIndex
 * @param titleIndex
 * @param imgIndex
 * @param tmpIndex
 * @param promptIndex
 */
function setFileUploader(fileTypeIndex, titleIndex, imgIndex, tmpIndex, promptIndex) {
    fileType = fileTypeArray[fileTypeIndex];
    title = titleArray[titleIndex];
    img = imgArray[imgIndex];
    template = templateArray[tmpIndex];
    promptInfo = promptInfoArray[promptIndex];
}


